<template>
  <div class="container">
    <div class="tabber">
      <a-space size="medium" direction="vertical" fill>
        <a-space>
          <a-input placeholder="请输入标题搜索" v-model="search"></a-input>
          <a-button type="primary" @click="handleSearch">
            <template #icon>
              <icon-search />
            </template>
            <template #default>搜索</template>
          </a-button>
          <a-select
            @change="handleToggle"
            style="width: 80px"
            v-model="searchType"
          >
            <a-option :value="0">全部</a-option>
            <a-option :value="1">图文</a-option>
            <a-option :value="2">视频</a-option>
          </a-select>
        </a-space>
        <a-space>
          <a-button
            type="primary"
            @click="
              visible = true;
              isAdd = true;
              form.type = 1;
              form.status = 1;
            "
          >
            <template #icon>
              <icon-plus />
            </template>
            <template #default>新增</template>
          </a-button>
          <a-button type="primary" @click="handleRefresh">
            <template #icon>
              <icon-loop />
            </template>
            <template #default>刷新</template>
          </a-button>
          <a-button
            status="danger"
            @click="deleteAll = selectedKeys.length > 0 ? true : false"
          >
            <template #icon>
              <icon-delete />
            </template>
            <template #default>批量删除</template>
          </a-button>
        </a-space>
      </a-space>
    </div>
    <a-table
      row-key="id"
      :columns="columns"
      :data="data"
      column-resizable
      :row-selection="rowSelection"
      v-model:selectedKeys="selectedKeys"
      :pagination="pagination"
      :bordered="{ cell: true }"
      :scroll="{ x: 'min-content' }"
      size="small"
      :table-layout-fixed="true"
    >
      <template #user="{ record }">
        {{ record.user.nikeName }}
      </template>
      <template #cover="{ record }">
        <a-image
          fit="cover"
          width="64"
          height="64"
          :src="BASE_URL + record.cover"
        />
      </template>
      <template #type="{ record }">
        <a-tag v-if="record.type === 1" color="#228be6"> 图文 </a-tag>
        <a-tag v-if="record.type === 2" color="#f59f00"> 视频 </a-tag>
        <a-tag v-if="record.type === 3" color="#f59f00"> 问答 </a-tag>
      </template>
      <template #solt="{ record }">
        <template v-if="record.type == 1">
          <a-carousel
            :style="{
              width: '160px',
              height: '90px',
            }"
          >
            <a-carousel-item
              v-for="(image, index) in record.atlas"
              :key="index"
            >
              <img
                :src="BASE_URL + image"
                :style="{
                  width: '100%',
                  height: '100%',
                  objectFit: 'cover',
                }"
              />
            </a-carousel-item>
          </a-carousel>
        </template>
        <template v-if="record.type == 2">
          <video
            :style="{
              width: '160px',
              height: '90px',
            }"
            controls
            :src="BASE_URL + record.videoUrl"
          ></video>
        </template>
      </template>
      <template #isShow="{ record }">
        <a-tag v-if="record.isShow === 1" color="arcoblue"> 公开 </a-tag>
        <a-tag v-if="record.isShow === 0" color="red"> 私密</a-tag>
      </template>
      <template #topics="{ record }">
        <a-tag
          style="margin: 4px"
          v-for="item in record.topics"
          :key="item.id"
          color="arcoblue"
        >
          {{ item.title }}
        </a-tag>
        <a-tag color="gray" v-if="record.topics.length === 0">无</a-tag>
      </template>
      <template #collectCount="{ record }">
        <a-tag color="gray"> {{ record.collectCount }} </a-tag>
      </template>
      <template #likeCount="{ record }">
        <a-tag color="gray"> {{ record.likeCount }} </a-tag>
      </template>
      <template #optional="{ record }">
        <a-button
          size="mini"
          type="primary"
          style="margin-right: 5px"
          @click="editorHanddle(record)"
          >编辑</a-button
        >
        <a-button size="mini" status="danger" @click="deleteHanddle(record)"
          >删除</a-button
        >
      </template>
    </a-table>
  </div>
  <!-- 编辑弹框 -->
  <a-modal
    v-model:visible="visible"
    :title="isAdd ? '添加数据' : '修改数据'"
    @cancel="handleCancel"
    @before-ok="handleBeforeOk"
  >
    <!-- <a-typography-text type="secondary" style="margin-left: 10vh;margin-bottom: 10px;">id:{{ form.id
        }}</a-typography-text> -->
    <a-form :model="form" style="padding-right: 40px">
      <a-form-item label="ID" v-if="!isAdd">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item label="正文">
        <a-textarea
          :auto-size="{ minRows: 6, maxRows: 8 }"
          placeholder="点击输入正文，您可在此交流骑行经验和生活，分享新鲜事"
          v-model="form.desc"
        />
      </a-form-item>
      <a-form-item label="作者" v-if="!isAdd">
        <a-input disabled :placeholder="form.user && form.user.nikeName" />
      </a-form-item>
      <a-form-item label="话题">
        <a-space direction="vertical" fill>
          <a-popover title="可选话题" trigger="click">
            <a-button
              v-if="
                form.topics == undefined ||
                (form.topics && form.topics.length < 3)
              "
            >
              <template #icon>
                <icon-plus />
              </template>
              <template #default>添加</template>
            </a-button>

            <template #content>
              <a-scrollbar style="height: 200px; overflow: auto">
                <p
                  @click="addTopic(item)"
                  v-for="item in topicList"
                  :key="item.id"
                  class="topic-item"
                >
                  {{ item.title }}
                </p>
              </a-scrollbar>
            </template>
          </a-popover>
          <a-tag
            closable
            size="large"
            v-for="item in form.topics"
            :key="item.id"
            @close="form.topics = form.topics.filter((i) => i.id !== item.id)"
          >
            <template #icon>
              <icon-star />
            </template>
            {{ item.title }}
          </a-tag>
        </a-space>
      </a-form-item>
      <a-form-item label="类型">
        <a-select v-model="form.type">
          <a-option :value="1">图文</a-option>
          <a-option :value="2">视频</a-option>
        </a-select>
      </a-form-item>

      <a-form-item label="图集" v-if="form.type == 1">
        <a-upload
          v-if="visible"
          list-type="picture-card"
          :action="BASE_URL + '/api/upload'"
          :default-file-list="
            isAdd
              ? []
              : form.atlas.map((item) => ({
                  uid: BASE_URL + item,
                  name: '20200717-103937.png',
                  url: BASE_URL + item,
                }))
          "
          @success="onUploadSuccess"
          @before-remove="beforeRemove"
          name="files"
          image-preview
          :limit="9"
        />
      </a-form-item>
      <a-form-item label="视频" v-if="form.type == 2">
        <a-upload
          v-if="visible"
          list-type="mp4"
          :action="BASE_URL + '/api/upload'"
          :default-file-list="
            isAdd
              ? []
              : form.videoUrl
              ? [
                  {
                    uid: BASE_URL + form.videoUrl,
                    name: '点击播放',
                    url: BASE_URL + form.videoUrl,
                  },
                ]
              : []
          "
          @beforeUpload="beforeUpload"
          @success="onUploadVideoSuccess"
          @before-remove="beforeVideoRemove"
          name="files"
          :limit="1"
        />
      </a-form-item>
      <a-form-item label="位置">
        <a-input v-model="form.address" />
      </a-form-item>

      <a-form-item label="状态">
        <a-select v-model="form.isShow">
          <a-option :value="1">公开可见</a-option>
          <a-option :value="0">仅自己可见</a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除弹框 -->
  <a-modal v-model:visible="delvalue" title="确认删除" @before-ok="delBeforeOk">
    <a-form :model="form">
      <a-form-item field="id" label="ID">
        <a-input disabled v-model="form.id" />
      </a-form-item>
      <a-form-item field="name" label="作者">
        <a-input disabled :placeholder="form.user?.nikeName" />
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 删除已选的 -->
  <a-modal v-model:visible="deleteAll" @before-ok="handleDeleteAll">
    <template #title> 警告 </template>
    <div>是否删除已选 {{ selectedKeys.length }} 项数据？</div>
  </a-modal>
</template>

<script setup>
import { BASE_URL } from "../../constant/index";
import { reactive, ref, onMounted } from "vue";
import {
  getDynamicListApi,
  deleteDynamicApi,
  addDynamicApi,
  updateDynamicApi,
} from "../../api/dynamic.js";
import { getTopicListApi } from "../../api/topic.js";
import {
  IconPlus,
  IconSearch,
  IconLoop,
  IconDelete,
} from "@arco-design/web-vue/es/icon";

import { Message } from "@arco-design/web-vue";

const rowSelection = reactive({
  type: "checkbox",
  showCheckedAll: false,
  onlyCurrent: false,
});
const pagination = { pageSize: 10 };
const columns = [
  {
    title: "id",
    dataIndex: "id",
    fixed: "left",
    width: 150,
    ellipsis: true,
    tooltip: true,
    align: "center",
  },
  {
    title: "作者",
    slotName: "user",
    width: 100,
    align: "center",
  },
  {
    title: "点赞量",
    slotName: "likeCount",
    // ellipsis: true,
    // tooltip: true,
    align: "center",
    width: 80,
  },
  {
    title: "收藏量",
    slotName: "collectCount",
    width: 80,
    align: "center",
  },
  {
    title: "状态",
    slotName: "isShow",
    width: 70,
    align: "center",
  },
  {
    title: "类型",
    slotName: "type",
    width: 70,
    align: "center",
  },

  {
    title: "图集/视频",
    slotName: "solt",
    width: 190,
    align: "center",
  },
  {
    title: "正文",
    dataIndex: "desc",
    width: 200,
    align: "center",
    ellipsis: true,
    tooltip: true,
  },
  {
    title: "话题",
    slotName: "topics",
    align: "center",
    width: 200,
  },
  {
    title: "地址",
    dataIndex: "address",
    align: "center",
    width: 200,
  },
  {
    title: "创建时间",
    dataIndex: "createdAt",
    width: 220,
    align: "center",
  },
  {
    title: "操作",
    fixed: "right",
    width: 200,
    slotName: "optional",
    align: "center",
  },
];

const data = ref([]);

const topicList = ref([]);
async function getTopicListData() {
  const getRes = await getTopicListApi({});
  console.log(getRes);
  if (getRes.code === 200) {
    topicList.value = getRes.data;
  } else {
    Message.error(getRes.msg);
  }
}
// 添加话题
async function addTopic(item) {
  console.log(item);
  if (!form.value.topics) {
    form.value.topics = [];
  }
  if (form.value.topics.length >= 3) {
    Message.info("最多添加三个话题");
    return;
  }
  const index = form.value.topics.findIndex(
    (i) => JSON.stringify(i) === JSON.stringify(item)
  );
  if (index !== -1) {
    Message.info("该话题已存在");
    return;
  } else {
    form.value.topics.push(item);
  }
  console.log(form.value.topics);
}
// 获取用户数据
async function getUserData() {
  const getRes = await getDynamicListApi({
    limit: 1000,
    page: 1,
    admin:true
  });
  console.log(getRes.data.list);
  if (getRes.code === 200) {
    data.value = getRes.data.list;
  }
}

// 获取用户数据
onMounted(() => {
  getUserData();
  // 获取话题列表
  getTopicListData();
});

//切换分类函数
async function handleToggle(type) {
  await getUserData();
  if (type !== 0) {
    data.value = data.value.filter((item) => {
      return item.type === type;
    });
  }
}

// 点击刷新按钮
function handleRefresh() {
  data.value = [];
  getUserData();
}
const deleteAll = ref(false);
// 已选择的数据
const selectedKeys = ref([]);
// 点击删除按钮
async function handleDeleteAll(done) {
  console.log(selectedKeys.value);
  const pra = selectedKeys.value.map((id) => {
    return new Promise(async (resolve, reject) => {
      const delRes = await deleteDynamicApi({ id });
      console.log(delRes);
      if (delRes.code === 200) {
        resolve(delRes);
      } else {
        reject(delRes);
      }
    });
  });
  try {
    await Promise.all(pra);
    Message.success("批量删除成功");
    done();
    getUserData();
  } catch (err) {
    Message.error("批量删除失败");
  }
  console.log("结束");

  return false;
}

const searchType = ref(0);
const search = ref("");
async function handleSearch() {
  await getUserData();
  data.value = data.value.filter((item) => {
    return item.desc.includes(search.value);
  });
}
// 上传图片回调
function onUploadSuccess(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const atlas = res.response.data[0];
    if (form.value.atlas == undefined) {
      form.value.atlas = [];
    }
    form.value.atlas.push(atlas);
  }
}
// 删除图片验证
function beforeRemove(file) {
  console.log(file);
  form.value.atlas = form.value.atlas.filter(
    (item) => "http://127.0.0.1:3000" + item != file.url
  );

  console.log(form.value.atlas);
  return true;
}
// 删除视频验证
function beforeVideoRemove(file) {
  form.value.videoUrl = "";
  return true;
}
// 上传视频回调
function onUploadVideoSuccess(res) {
  console.log(res.response);
  if (res.response.code === 200) {
    const videoUrl = res.response.data[0];
    form.value.videoUrl = videoUrl;
  }
}

// 显示编辑弹框
const visible = ref(false);
const form = ref({});
const isAdd = ref(false);
// 取消弹框
function handleCancel() {
  isAdd.value = false;
  form.value = {};
}
// 点击编辑按钮
function editorHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  //   form.value = item;
  visible.value = true;
}
// 确认修改按钮
async function handleBeforeOk(done) {
  if (isAdd.value) {
    await handleAdd(done);
  } else {
    await handleUpdate(done);
  }
  // form.value = {};
  return false;
}
// 验证上传文件是否是视频
function beforeUpload(file) {
  return new Promise((resolve, reject) => {
    if (file.type.indexOf("video") === -1) {
      Message.error("上传文件必须为视频格式");
      reject(false);
    } else {
      resolve(true);
    }
  });
}
// 新增逻辑
async function handleAdd(done) {
  console.log(form.value);
  const { desc, type, atlas, videoUrl,videoCover, address, topics = [],  isShow, } = form.value;

  if (!desc) {
    Message.error("请输入正文");
    return false;
  }
  console.log(isShow);
  if (isShow === undefined) {
    Message.error("请选择状态");
    return false;
  }
  if (type == 2) {
    if (!videoUrl) {
      Message.error("视频地址不能为空");
      return false;
    }
  }
  console.log(topics);
  // 获取话题id
  const topicId = [];
  for (let i = 0; i < topics.length; i++) {
    const element = topics[i];
    topicId.push(element.id);
  }
  const addRes = await addDynamicApi({ desc,  type,  atlas,  videoUrl,  videoCover,  address,  topicId, isShow,
});
  console.log(addRes);
  if (addRes.code === 200) {
    Message.success("新增成功");
    await getUserData();
    form.value = {};
    done();
  } else {
    console.log(postRes);
    Message.error(postRes.message);
    return false;
  }
}
// 更新逻辑
async function handleUpdate(done) {
  console.log(form.value);
  const {
    id,
    desc,
    type,
    atlas,
    videoUrl,
    videoCover,
    address,
    topics = [],
    isShow,
  } = form.value;

  if (!desc) {
    Message.error("请输入正文");
    return false;
  }
  console.log(isShow);
  if (isShow === undefined) {
    Message.error("请选择状态");
    return false;
  }
  if (type == 2) {
    if (!videoUrl) {
      Message.error("视频地址不能为空");
      return false;
    }
  }
  console.log(topics);
  // 获取话题id
  const topicId = [];
  for (let i = 0; i < topics.length; i++) {
    const element = topics[i];
    topicId.push(element.id);
  }
  const updataRes = await updateDynamicApi({
    id,
    desc,
    type,
    atlas,
    videoUrl,
    videoCover,
    address,
    topicId,
    isShow,
  });
  console.log(updataRes);
  if(updataRes.code === 200){
    Message.success("修改成功");
    getUserData();
    done();
  }else{
    Message.error("修改失败");
    return false;
  }
}

// 删除弹框
const delvalue = ref(false);
// 点击删除按钮
function deleteHanddle(item) {
  console.log(item);
  form.value = JSON.parse(JSON.stringify(item));
  delvalue.value = true;
}
// 确认删除
async function delBeforeOk() {
  const { id } = form.value;
  console.log(id);
  const delRes = await deleteDynamicApi({ id });
  console.log(delRes);
  if (delRes.code === 200) {
    Message.info("删除成功");
    // 更新数据
    getUserData();
    delvalue.value = false;
  } else {
    Message.error("删除失败");
    return false;
  }
}
</script>

<style lang="less" scoped>
.container {
  padding: 14px;
  box-sizing: border-box;
  .tabber {
    padding-bottom: 14px;
  }
}
.container :deep(td) {
  // display: flex;
  // align-items: center;
  vertical-align: middle;
}
.topic-item {
  // background-color: red;
  padding: 4px 14px;
  // border-radius: 4px;
  &:hover {
    background-color: #f2f3f5;
    cursor: pointer;
  }
}
</style>
